//
//  SHJavaScriptCoreViewController.m
//  SDemo
//
//  Created by gg on 2018/7/20.
//  Copyright © 2018年 gg. All rights reserved.
//

#import "SHJavaScriptCoreViewController.h"
#import "SHJSNextViewController.h"
@interface SHJavaScriptCoreViewController ()<UIWebViewDelegate,JSNativeDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UIWebView *webview;
@property(nonatomic,weak)JSContext *content;
@property(nonatomic,strong)UITextField *textfield;

@end

@implementation SHJavaScriptCoreViewController

-(UIWebView *)webview {
    if (_webview == nil) {
        _webview = [[UIWebView alloc] init];
        _webview.delegate = self;
        _webview.backgroundColor  = [UIColor yellowColor];
        // UIWebView 滚动的比较慢，这里设置为正常速度
        _webview.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    }
    
    return  _webview;
}

-(UITextField *)textfield {
    if (_textfield == nil) {
        _textfield = [[UITextField alloc] init];
        _textfield.delegate = self;
        _textfield.placeholder = @"请输入文字";
        _textfield.borderStyle = UITextBorderStyleRoundedRect;
    }
    return  _textfield;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"JavaScriptCore";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.webview];
   // [self.view addSubview:self.textfield];
    
    [self.webview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(64);
      //  make.bottom.mas_equalTo(self.textfield.mas_top).mas_offset(20);
    }];
    
//    [self.textfield mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(CGSizeMake(150, 45));
//        make.bottom.mas_equalTo(-20);
//        make.centerY.mas_equalTo(self.view);
//    }];
    

    //runtime
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index3" ofType:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [self.webview loadRequest:request];

    //[self initData];
   // [self initJSExport];
    
    [self jsChange];
}

-(void)jsChange {
    void(^myblock)(NSString* ) = ^(NSString * name) {
        NSLog(@"name : %@",name);
    };
    myblock(@"kobe");
    
    
}


-(void)initData {
    //1 JSContext / JSValue
    JSContext *jsC = [[JSContext alloc] init];
    [jsC evaluateScript:@"var num = 4 * 2"];
    [jsC evaluateScript:@"var name = ['james','kobe','paul']"];
    [jsC evaluateScript:@"var firstClick = function (value) { return value * value }"];
    JSValue *value = [jsC evaluateScript:@"firstClick(num)"];
    NSLog(@"value :%d",value.toInt32); // 64
    
    //2 使用下标取值
    JSValue *names = jsC[@"name"];
    JSValue *name = names[1];
    NSLog(@"name : %@", name.toString);
    //3  JSValue 包装了一个 JavaScript 函数，我们可以从 Objective-C / Swift 代码中使用 Foundation 类型作为参数来直接调用该函数。再次，JavaScriptCore 很轻松的处理了这个桥接
    JSValue *first = jsC[@"firstClick"];
    JSValue *result = [first callWithArguments:@[@9]];
    NSLog(@"result : %d",result.toInt32); // 81
    
    //4 错误处理 ：通过设置上下文的 exceptionHandler 属性，你可以观察和记录语法，类型以及运行时错误。 exceptionHandler 是一个接收一个 JSContext 引用和异常本身的回调处理：
    jsC.exceptionHandler = ^(JSContext *con, JSValue *exception) {
        NSLog(@"%@", exception);
        con.exception = exception;
    };
    
    //javaScript 调用
    jsC[@"share"] = ^() {
        NSLog(@"分享到QQ空间");
    };
    
    JSValue *share = [jsC evaluateScript:@"share()"];
    NSLog(@"share : %@",share);
    
    
}

-(void)initJSExport {
    //JSExport 协议
    
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    self.content = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    //异常信息捕捉
    self.content.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        context.exception = exception;
        NSLog(@"异常信息捕捉：%@",exception);
    };
    
    /**
     方式1 ： 直接调用的函数
     */
    //获取点击事件
    __weak typeof(self)weakSel = self;
    self.content[@"passValue"] = ^(NSString *name) {
        [weakSel showAlter:[NSString stringWithFormat:@"获取到的值：%@",name]];
        NSLog(@"我点击了传值： %@",name);
    };

    /**
     方式二：通过native调用的方式
     需要声明一个JSExport的协议，协议中声明供JS使用的方法
     注： 在JS调用的方法里实现页面跳转时，要回到主线程执行。
     */
    self.content[@"Native"] = self;
//    class_addProtocol([UITextField class], @protocol(JSNativeDelegate));
//    self.content[@"iOSTextField"] = self.textfield;
    
    
    /**
     oc 调 js的方法
     第一种 方法
     */
//    JSValue *callback = self.content[@"alertShow"];
//    [callback callWithArguments:@[@"oc 调用js 方法"]];
    
    //第二种方法
    [self.content evaluateScript:@"alertShow('oc 调用js 方法')"];
    
    
}


//实现协议方法
- (void)call:(NSString *)cell {
    [self showAlter:[NSString stringWithFormat:@"获取到的值：%@",cell]];
    NSLog(@"原生方法调用%@",cell);
}

-(void)showAlter:(NSString *)msg{
    UIAlertController *alterC = [UIAlertController alertControllerWithTitle:@"方式一" message:msg preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *cancal = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alterC addAction:cancal];
    [self presentViewController:alterC animated:YES completion:nil];
    
}

//跳转
-(void)pushClass {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController pushViewController:[SHJSNextViewController new] animated:YES];
    });
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
